﻿using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;

namespace ByteArray
{
    public class Processor : IProcessor
    {
        private List<string> _sensitiveWords;
        private Dictionary<string, int> _wordCounts;

        public Processor(SensitiveResearchOption option)
        {
            _sensitiveWords = new List<string>(option.Keywords);
            _wordCounts = new Dictionary<string, int>();
        }

        private void WordCounts(string text)
        {
            foreach (var word in _sensitiveWords)
            {
                if (!_wordCounts.ContainsKey(word))
                {
                    _wordCounts[word] = 0;
                }

                int count = 0;
                int index = 0;
                while ((index = text.IndexOf(word, index, StringComparison.Ordinal)) != -1)
                {
                    index += word.Length;
                    count++;
                }
                _wordCounts[word] += count;
            }
        }


        public (string processedbuffer, string processedtext) Check(string text)
        {
            string processedText = null;
            WordCounts(text);
            foreach (var word in _sensitiveWords)
            {
                    int index = text.IndexOf(word);
                    if (index == -1)
                    {
                        if (text.Length > word.Length - 1)
                        {
                            processedText = text.Substring(0, text.Length - word.Length );
                            text = text.Substring(text.Length - word.Length );
                        }
                        break;
                    }
                    processedText = text.Substring(0, index) + "xjy";
                    text = text.Remove(0, index + word.Length);
            }
            return (text, processedText);           
        }

        public Dictionary<string, int> GetWordCounts()
        {
            return new Dictionary<string, int>(_wordCounts);
        }
    }
}